package com.fingard.dsp.bank.directbank.crbc01;

import java.util.Date;

import com.fingard.dsp.bank.directbank.bankInterface.IElecBillQuery;
import com.fingard.dsp.bank.reqrespobj.elecbillquery.*;
import com.fingard.dsp.bank.reqrespobj.elecbillquery.detail.RetAtsB001OperBillQryDetail;
import com.fingard.dsp.bank.reqrespobj.elecbillquery.detail.RetAtsB005BillBackQryDetail;
import com.fingard.dsp.bank.reqrespobj.elecbillquery.detail.RetAtsB006BillStateQryDetail;
import com.fingard.dsp.bank.reqrespobj.elecbillquery.detail.RetAtsB007BillKzsrQryDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2019/1/27.
 */
public class CRBC01ElecBill extends CRBC01Base implements IElecBillQuery {
    @Override
    public RetAtsB001OperBillQry D_OperBill_Query_Req(ReqB001OperBillQry query) throws Exception {
        RetAtsB001OperBillQry retAts = new RetAtsB001OperBillQry(query.reqHeader);
        retAts.writeStart();
        query.readRecord();
        int pageNum = getBankConfig().getValueAsInt("eleQryPageNum");
        if(-1==pageNum){
            pageNum =50;
        }
        int page = 0;
        int tmpReadNum = 0;//已查询笔数
        int tmpTotalNum = 0;//记录总数
            try {
                do {
                    page++;
                    XmlTextWriter xmlWriter = new XmlTextWriter();
                    CRBC01Header header = new CRBC01Header();
                    header.tranTime = new Date();
                    header.tranCode = "110084";
                    writeCommonHeader(xmlWriter, header);
                    xmlWriter.writeStartElement("BODY");
//            stdqrycont	查询内容	★	2	VARCHAR2	"23 出票查询
//            04 - 撤票
//            05 - 背书
//            06 - 贴现
//            15 - 质押
//            16 - 质押解除
//            17 - 提示付款
//            18 - 逾期提示付款
//            19 - 拒付追索通知
//            20 - 非拒付追索
//            21 - 追索同意清偿请求"
                    String buscode;
                    switch (Integer.valueOf(query.detail.busiType)) {
                        case 1:
                            buscode = "04";
                            break;
                        case 2:
                            buscode = "23";
                            break;
                        case 3:
                            buscode = "23";
                            break;
                        case 4:
                            buscode = "05";
                            break;
                        case 5:
                            buscode = "15";
                            break;
                        case 6:
                            buscode = "16";
                            break;
                        case 10:
                            buscode = "06";
                            break;
                        case 11:
                            buscode = "07";
                            break;
                        case 12:
                            if(!"2".equals(query.detail.queryType)){
                            if ("1".equals(query.detail.overdueFlag)) {
                                buscode = "17";
                            } else {
                                buscode = "18";
                                }
                            }else{
                                buscode = "24";
                            }
                            break;
                        case 13:
                            if ("1".equals(query.detail.recourseType)) {
                                buscode = "19";
                            } else {
                                buscode = "20";
                            }
                            break;
                        case 14:
                            buscode = "21";
                            break;
                        default:
                            throw new Exception("未知的业务类型：" + query.detail.busiType);
                    }
                    String stdtrastat;
                    String stdsendflg = "01";
                    if ("3".equals(query.detail.queryType)) {
                        if("1".equals(query.detail.busiType)){
                            stdtrastat = "0";
                        }else {
                            stdtrastat = "1";
                        }
                    } else {
                        stdtrastat = "0";
                        if ("2".equals(query.detail.queryType)) {
                            stdsendflg = "02";
                        }
                    }
                    xmlWriter.writeElementString("stdqrycont", buscode);
//            stdtrastat	交易状态	★	1	VARCHAR2	"0可操作（发起申请交易时）
                    xmlWriter.writeElementString("stdtrastat", stdtrastat);
//            1正在操作（撤销申请交易时）"
//            stdsendflg	发送方标志	★	2	VARCHAR2	"01发起方（查询所有可发起的交易）
                    xmlWriter.writeElementString("stdsendflg", stdsendflg);
//            02接收方（查询所有可签收的交易）"
//            stdcustcod	客户组织机构代码证	★	20	VARCHAR2	"对于发送方标志为01发起方时填写
                    if ("01".equals(stdsendflg)) {
                        xmlWriter.writeElementString("stdcustcod", bankFront.org);
                    } else {
                        xmlWriter.writeElementString("stdcustcod", "");
                    }
//            对于发送方标志为02接收方时不填写"
//            stdcustacc	账号	★	32	VARCHAR2
                    xmlWriter.writeElementString("stdcustacc", query.detail.actNum);
//            stdcustbnm	客户行号	★	12	VARCHAR2
                    xmlWriter.writeElementString("stdcustbnm", "");
//            stdbilattr	票据属性	★	1	VARCHAR2	2-电子
                    xmlWriter.writeElementString("stdbilattr", "2");
//            stdbillnum	电子票据序列号		30	VARCHAR2	票据号码
                    xmlWriter.writeElementString("stdbillnum", "");
//            BEGINPOS	翻页数据起始位置	★	10	VARCHAR2
                    xmlWriter.writeElementString("BEGINPOS", page + "");
//            SHOWNUM	翻页一次显示数量	★	10	VARCHAR2
                    xmlWriter.writeElementString("SHOWNUM", pageNum+"");
//            stdtransno	交易流水号	★	30	VARCHAR2
                    xmlWriter.writeElementString("stdtransno", query.reqHeader.transSeqID);
                    xmlWriter.writeEndDocument();
                    String[] bankResult = sendToBank(xmlWriter.toXmlString());
                    if (bankResult[0].length() == 0) {
                        StringBuilder tmpsbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpsbMsg);
                        if (tmpBkReader != null) {
                            String resultCode = tmpBkReader.getFirstText("/CRBANK/HEAD/RET_CODE");
                            String resultMsg = tmpBkReader.getFirstText("/CRBANK/HEAD/RET_Msg");
                            if ("000000".equals(resultCode)) {
                                retAts.respCode = "0";
                                retAts.respInfo = resultMsg;
                                if (tmpTotalNum == 0) {
                                    tmpTotalNum = Integer.valueOf(tmpBkReader.getFirstText("/CRBANK/BODY/TOTALNUM"));
                                }
                                while (tmpBkReader.read("/CRBANK/BODY/bill_array/STRUCT")) {
                                    tmpReadNum++;
                                    String billType = "AC01".equals(tmpBkReader.readedXElement.getSingleText("stdbilltyp")) ? "1" : "2";
                                    if(!billType.equals(query.detail.billType)){
                                        continue;
                                    }
                                    //stdinfotyp
                                    String queryType = tmpBkReader.readedXElement.getSingleText("stdinfotyp");
                                    if ("2".equals(query.detail.busiType) && !"02".equals(queryType)) {
                                        continue;
                                    } else if ("3".equals(query.detail.busiType) && !"03".equals(queryType)) {
                                        continue;
                                    }
                                    String stdbusstyp = tmpBkReader.readedXElement.getSingleText("stdbusstyp");
                                    if("17".equals(buscode)&&!"01".equals(stdbusstyp)){
                                        continue;
                                    }
                                    else if("18".equals(buscode)&&!"02".equals(stdbusstyp)){
                                        continue;
                                    }
                                    RetAtsB001OperBillQryDetail detail = new RetAtsB001OperBillQryDetail();
                                    if("01".equals(stdbusstyp)){
                                        detail.overDueFlag = "1";
                                    }else if("02".equals(stdbusstyp)){
                                        detail.overDueFlag = "2";
                                    }
//                            std
// billnum	电子票据序列号		30	VARCHAR2
                                    detail.billNo = tmpBkReader.readedXElement.getSingleText("stdbillnum");
//                            stdissdate	出票日		8	VARCHAR2
                                    detail.issDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleText("stdissdate"));
//                            stdduedate	到期日		8	VARCHAR2
                                    detail.dueDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleText("stdduedate"));
//                            stdbilltyp	票据类型		4	VARCHAR2	"AC01银承  AC02商承
                                    detail.billType = "AC01".equals(tmpBkReader.readedXElement.getSingleText("stdbilltyp")) ? "EM001" : "EM002";
//                            stdpmmoney	票面金额		15,2	NUMBER
                                    detail.billAmt = tmpBkReader.readedXElement.getSingleText("stdpmmoney");
//                            stdendormk	转让标记		4	VARCHAR2	"EM00可再转让
//                            EM01不得转让"
                                    detail.transFlag = "EM00".equals(tmpBkReader.readedXElement.getSingleText("stdendormk")) ? "1" : "0";
//                            stduncnpay	到期无条件支付委托		4	VARCHAR2	只能填写CC00
                                    detail.mustPay = "CC00".equals(tmpBkReader.readedXElement.getSingleText("stduncnpay")) ? "1" : "";
//                            stdbussqno	业务流水标识		10	VARCHAR2	做为接收方查询时返回
                                    detail.busiNo = tmpBkReader.readedXElement.getSingleText("stdbussqno");
//                            stddrwrnam	出票人名称		60	VARCHAR2
                                    detail.drawName = tmpBkReader.readedXElement.getSingleText("stddrwrnam");
//                            stddrwrcod	出票人组织机构代码证		20	VARCHAR2
                                    detail.drawCode = tmpBkReader.readedXElement.getSingleText("stddrwrcod");
//                            stddrwracc	出票人开户帐户		32	VARCHAR2
                                    detail.drawAct = tmpBkReader.readedXElement.getSingleText("stddrwracc");
//                            stddrwrbnm	出票人开户行行号		12	VARCHAR2
                                    detail.drawBnkCode = tmpBkReader.readedXElement.getSingleText("stddrwrbnm");
//                            stdaccpnam	承兑人名称		60	VARCHAR2
                                    detail.accpName = tmpBkReader.readedXElement.getSingleText("stdaccpnam");
//                            stdaccpcod	承兑人组织机构代码证		20	VARCHAR2
                                    detail.accpCode = tmpBkReader.readedXElement.getSingleText("stdaccpcod");
//                            stdaccpacc	承兑人开户帐户		32	VARCHAR2
                                    detail.accpAct = tmpBkReader.readedXElement.getSingleText("stdaccpacc");
//                            stdaccpbnm	承兑人开户行行号		12	VARCHAR2
                                    detail.accpBnkCode = tmpBkReader.readedXElement.getSingleText("stdaccpbnm");
//                            stdpyeenam	收款人名称		60	VARCHAR2
                                    detail.payeeName = tmpBkReader.readedXElement.getSingleText("stdpyeenam");
//                            stdpyeecod	收款人组织机构代码证		20	VARCHAR2
                                    detail.payeeCode = tmpBkReader.readedXElement.getSingleText("stdpyeecod");
//                            stdpyeeacc	收款人开户帐户		32	VARCHAR2
                                    detail.payeeAct = tmpBkReader.readedXElement.getSingleText("stdpyeeacc");
//                            stdpyeebnm	收款人开户行行号		12	VARCHAR2
                                    detail.payeeBnkCode = tmpBkReader.readedXElement.getSingleText("stdpyeebnm");
//                            <stdbilstatCode>010004</stdbilstatCode>	票据状态		6	VARCHAR2	"01- 出票未登记
                                    detail.billStatus = tmpBkReader.readedXElement.getSingleText("stdbilstatCode");
//                            stdrcrstyp	追索类型		4	VARCHAR2	"RT00拒付追索
//                            RT01非拒付追索"
                                    String recType = tmpBkReader.readedXElement.getSingleText("stdrcrstyp");
                                    if (StringHelper.hasAnyChar(recType)) {
                                        detail.recourseType = "RT00".equals(recType) ? "1" : "2";
                                    }
//                            stdrcrsamt	追索金额		15,2	NUMBER
                                    detail.recourseAmt = tmpBkReader.readedXElement.getSingleText("stdrcrsamt");
//                            stdappdate	申请日期		8	VARCHAR2
                                    String applyDate = tmpBkReader.readedXElement.getSingleText("stdappdate");
                                    detail.applyDate = DateHelper.convertD8toD10(applyDate);
//                            stdapptype	申请人类型		4	VARCHAR2
//                            stdappname	申请人名称		60	VARCHAR2
                                    detail.applyName = tmpBkReader.readedXElement.getSingleText("stdappname");
//                            stdappacct	申请人账号		32	VARCHAR2
                                    detail.applyAct = tmpBkReader.readedXElement.getSingleText("stdappacct");
//                            stdappcode	申请人组织机构代码		20	VARCHAR2
//                            stdappbnm	申请人行号		12	VARCHAR2
                                    detail.applyBnkCode = tmpBkReader.readedXElement.getSingleText("stdappbnm");
//                            stdrcvtype	接收人类型		4	VARCHAR2
//                            stdrcvname	接收人名称		60	VARCHAR2
                                    detail.receName = tmpBkReader.readedXElement.getSingleText("stdrcvname");
//                            stdrcvacct	接收人账号		32	VARCHAR2
                                    detail.receAct = tmpBkReader.readedXElement.getSingleText("stdrcvacct");
//                            stdrcvcode	接收人组织机构代码		20	VARCHAR2
//                            stdrcvbnm	接收人行号		12	VARCHAR2
                                    detail.receBnkCode = tmpBkReader.readedXElement.getSingleText("stdrcvbnm");
                                    retAts.writeDetail(detail);
                                }
                            } else {
                                throw new Exception(resultMsg);
                            }
                        } else {
                            throw new Exception(tmpsbMsg.toString());
                        }
                    } else {
                        throw new Exception(bankResult[1]);
                    }
                }while (tmpReadNum<tmpTotalNum);
            } catch (Exception ex) {
                ex.printStackTrace();
                retAts.respCode = "-1";
                retAts.respInfo = ex.getMessage();
            }
        retAts.writeRespCode(retAts.respCode);
        retAts.writeRespInfo(retAts.respInfo);
        retAts.writeAfter();
        return retAts;
    }

    @Override
    public RetAtsB002BillTransQry D_B002_BillTrans_Query(ReqB002BillTransQry query) throws Exception {
        return null;
    }

    @Override
    public RetAtsB004BillFrontQry D_B004_BillFront_Query(ReqB004BillFrontQry query) throws Exception {
        RetAtsB004BillFrontQry retAts = new RetAtsB004BillFrontQry(query.reqHeader);
        retAts.writeStart();
        query.readRecord();
        try{
            XmlTextWriter xmlWriter = new XmlTextWriter();
            CRBC01Header header = new CRBC01Header();
            header.tranCode = "110086";
            header.tranTime = new Date();
            writeCommonHeader(xmlWriter,header);
            xmlWriter.writeStartElement("BODY");
//            stdqrycont	客户账号	★	32	VARCHAR2
            xmlWriter.writeElementString("stdqrycont",query.detail.actNum);
//            stdcustcod	客户开户行号	★	12	VARCHAR2
            xmlWriter.writeElementString("stdcustcod","");
//            stdcustacc	电子票据号码	☆	30	VARCHAR2
            xmlWriter.writeElementString("stdcustacc",query.detail.billNo);
//            stdcustbnm	行为人角色	★	4	VARCHAR2	非必填
            xmlWriter.writeElementString("stdcustbnm","");
//            BEGINPOS	翻页数据起始位置	★	10	VARCHAR2
            xmlWriter.writeElementString("BEGINPOS", "1");
//            SHOWNUM	翻页一次显示数量	★	10	VARCHAR2
            xmlWriter.writeElementString("SHOWNUM", "10");
//            stdtransno	交易流水号	★	30	VARCHAR2
            xmlWriter.writeElementString("stdtransno",getQryTransID());
            xmlWriter.writeEndDocument();
            String[] result  = sendToBank(xmlWriter.toXmlString());
            if(result[0].length() ==0){
                StringBuilder tmpsbMsg = new StringBuilder();
                XmlTextReader tmpbkReader =loadBankRespXmlReader(result[1],tmpsbMsg);
                if(tmpbkReader!=null){
                    String returnCode = tmpbkReader.getFirstText("/CRBANK/HEAD/RET_CODE");
                    String resultMsg = tmpbkReader.getFirstText("/CRBANK/HEAD/RET_Msg");
                    if("000000".equals(returnCode)){
                        while (tmpbkReader.read("/CRBANK/BODY/bill_array/STRUCT")){
                            retAts.respCode ="0";
                            retAts.respInfo =resultMsg;
//                            elcDraftId	电子票据号码		30	VARCHAR2
                            retAts.billNo = tmpbkReader.readedXElement.getSingleText("elcDraftId");
//                            draftAmount	票面金额		15,2	NUMBER
                            retAts.billAmt = tmpbkReader.readedXElement.getSingleText("draftAmount");
//                            remitDate	出票日		8	VARCHAR2
                            retAts.issDate = DateHelper.convertD8toD10(tmpbkReader.readedXElement.getSingleText("remitDate"));
//                            maturityDate	到期日		8	VARCHAR2	"AC01银承 AC02商承"
                            retAts.dueDate = DateHelper.convertD8toD10(tmpbkReader.readedXElement.getSingleText("maturityDate"));
//                            draftType	票据类型		4	VARCHAR2
                            retAts.billType = "AC01".equals(tmpbkReader.readedXElement.getSingleText("draftType"))?"1":"2";
//                            remitterNm	出票人名称		60	VARCHAR2
                            retAts.drawName = tmpbkReader.readedXElement.getSingleText("remitterNm");
//                            payeeNm	收款人名称		60	VARCHAR2	只能填写CC00
                            retAts.payeeName = tmpbkReader.readedXElement.getSingleText("payeeNm");
//                            acceptorNm	承兑人名称		60	VARCHAR2	做为接收方查询时返回
                            retAts.accpName = tmpbkReader.readedXElement.getSingleText("acceptorNm");
//                            transferFlag	是否可转让标志		4	VARCHAR2	"RC00银行
                            retAts.transFlag = "EM00".equals(tmpbkReader.readedXElement.getSingleText("transferFlag"))?"1":"2";
//                            remitterBrchCode	出票人组织结构代码		20	VARCHAR2
                            retAts.drawCode = tmpbkReader.readedXElement.getSingleText("remitterBrchCode");
//                            remitterAccount	出票人账号		32	VARCHAR2
                            retAts.drawAct = tmpbkReader.readedXElement.getSingleText("remitterAccount");
//                            remitterBankId	出票人开户行行号		12	VARCHAR2
                            retAts.drawBnkCode = tmpbkReader.readedXElement.getSingleText("remitterBankId");
//                            remitterBankName	出票人开户行名称		60	VARCHAR2
                            retAts.drawBnkName = tmpbkReader.readedXElement.getSingleText("remitterBankName");
//                            payeeAccount	收款人账号		32	VARCHAR2
                            retAts.payeeAct = tmpbkReader.readedXElement.getSingleText("payeeAccount");
//                            payeeBankId	收款人开户行行号		12	VARCHAR2	"RC00银行
                            retAts.payeeBnkCode = tmpbkReader.readedXElement.getSingleText("payeeBankId");
//                            payeeBankName	收款人开户行名称		60	VARCHAR2
                            retAts.payeeBnkName = tmpbkReader.readedXElement.getSingleText("payeeBankName");

//                            acceptorBankId	承兑人开户行行号		12	VARCHAR2
                            retAts.accpBnkCode = tmpbkReader.readedXElement.getSingleText("acceptorBankId");
//                            acceptorAccount	承兑人账号		32	VARCHAR2
                            retAts.accpAct = tmpbkReader.readedXElement.getSingleText("acceptorAccount");
//                            acceptorBankName	承兑人开户行名称		60	VARCHAR2
                            retAts.accpBnkName = tmpbkReader.readedXElement.getSingleText("acceptorBankName");
//                            stdbilstatCode	人行票据状态（代码）		6	VARCHAR2
                            retAts.billState = tmpbkReader.readedXElement.getSingleText("stdbilstatCode");

                        }
                    }

                }else{
                    retAts.respInfo = tmpsbMsg.toString();
                    retAts.respCode = "-1";
                }
            }else {
                retAts.respCode= "-1";
                retAts.respInfo= result[1];
            }
        }catch (Exception ex ){
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
        }
        retAts.writeRetDetail();
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsB005BillBackQry D_B005_BillBack_Query(ReqB005BillBackQry query) throws Exception {
        RetAtsB005BillBackQry retAts = new RetAtsB005BillBackQry(query.reqHeader);
        retAts.writeStart();
        query.readRecord();
        RetAtsB005BillBackQryDetail detail = new RetAtsB005BillBackQryDetail();
        int pageNum = getBankConfig().getValueAsInt("eleQryPageNum");
        if(-1==pageNum){
            pageNum =50;
        }
        int tmpReadedNum = 0;
        int page =0;
        int totalNum = 0;
        try {
            do {
                page++;
                XmlTextWriter xmlWriter = new XmlTextWriter();
                CRBC01Header header = new CRBC01Header();
                header.tranCode = "110087";
                header.tranTime = new Date();
                writeCommonHeader(xmlWriter, header);
                xmlWriter.writeStartElement("BODY");
//            stdqrycont	客户账号	★	32	VARCHAR2
            xmlWriter.writeElementString("stdqrycont",query.detail.actNum);
//            stdcustcod	客户开户行号	★	12	VARCHAR2
            xmlWriter.writeElementString("stdcustcod","");
//            stdcustacc	电子票据号码	★	30	VARCHAR2
            xmlWriter.writeElementString("stdcustacc",query.detail.billNo);
//            BEGINPOS	翻页数据起始位置	★	10	VARCHAR2
                xmlWriter.writeElementString("BEGINPOS", page + "");
//            SHOWNUM	翻页一次显示数量	★	10	VARCHAR2
                xmlWriter.writeElementString("SHOWNUM", pageNum+"");
//            stdtransno	交易流水号	★	30	VARCHAR2
                xmlWriter.writeElementString("stdtransno", getQryTransID());
                xmlWriter.writeEndDocument();
                String[] result = sendToBank(xmlWriter.toXmlString());
                if (result[0].length() == 0) {
                    StringBuilder tmpsbMsg = new StringBuilder();
                    XmlTextReader tmpbkReader = loadBankRespXmlReader(result[1], tmpsbMsg);
                    if (tmpbkReader != null) {
                        String returnCode = tmpbkReader.getFirstText("/CRBANK/HEAD/RET_CODE");
                        String resultMsg = tmpbkReader.getFirstText("/CRBANK/HEAD/RET_Msg");
                        if ("000000".equals(returnCode)) {
                           String totalStr =tmpbkReader.getFirstText("/CRBANK/BODY/TOTALNUM");
                            if(totalNum==0){
                                totalNum =Integer.valueOf(totalStr);
                            }
                            if(StringHelper.isNullOrEmpty(totalStr)||"0".equals(totalStr)){
                                break;
                            }
                            while (tmpbkReader.read("/CRBANK/BODY/bill_array/STRUCT")) {
                                RetAtsB005BillBackQryDetail backDetail = new RetAtsB005BillBackQryDetail();
                                switch (Integer.valueOf(tmpbkReader.readedXElement.getSingleText("stdinfotyp"))) {
                                    case 1:
                                        backDetail.transCode = "2";
                                        break;
                                    case 2:
                                        backDetail.transCode = "3";
                                        break;
                                    case 3:
                                        backDetail.transCode = "10";
                                        break;
                                    case 4:
                                        backDetail.transCode = "11";
                                        break;
                                    case 5:
                                        backDetail.transCode = "12";
                                        break;
                                    case 6:
                                        backDetail.transCode = "13";
                                        break;
                                    case 7:
                                        backDetail.transCode = "14";
                                        break;
                                    case 8:
                                        backDetail.transCode = "15";
                                        break;
                                    case 9:
                                        backDetail.transCode = "16";
                                        break;
                                    case 11:
                                        backDetail.transCode = "17";
                                        break;
                                    case 12:
                                        backDetail.transCode = "18";
                                        break;
                                    case 13:
                                        backDetail.transCode = "19";
                                        break;
                                    case 14:
                                        backDetail.transCode = "20";
                                        break;
                                    case 15:
                                        backDetail.transCode = "21";
                                        break;
                                    case 16:
                                        backDetail.transCode = "22";
                                        break;
                                    default:
                                        continue;
                                }
                                backDetail.respCode = "0";
//                            stdappdate	申请日期		8	VARCHAR2
                            backDetail.applyDate = DateHelper.convertD8toD10(tmpbkReader.readedXElement.getSingleText("stdappdate"));
//                            stdappname	请求方名称		60	VARCHAR2
                            backDetail.applyName = tmpbkReader.readedXElement.getSingleText("stdappname");
//                            stdrcvname	接收方名称		60	VARCHAR2
                            backDetail.receName = tmpbkReader.readedXElement.getSingleText("stdrcvname");
//                            stdrpdopdt	赎回截止日		8	VARCHAR2
                            String opdt = tmpbkReader.readedXElement.getSingleText("stdrpdopdt");
                            if(StringHelper.hasAnyChar(opdt)){
                                backDetail.repDueDate = DateHelper.convertD8toD10(opdt);
                            }
//                            stdrpddudt	赎回开放日		8	VARCHAR2
                            String dudt = tmpbkReader.readedXElement.getSingleText("stdrpddudt");
                            if(StringHelper.hasAnyChar(dudt)){
                                backDetail.repOpenDate = DateHelper.convertD8toD10(dudt);
                            }
//                            stddshnrcd	拒付代码		2	VARCHAR2	"提示付款、逾期提示付款
                            String nrcd = tmpbkReader.readedXElement.getSingleText("stddshnrcd");
                            if(StringHelper.hasAnyChar(nrcd)){
                                if("10".equals(nrcd)){
                                  backDetail.unPayCode = "99";
                                }else {
                                    detail.unPayCode = nrcd.substring(1);
                                }
                            }
//                            01、与自己有直接债权债务关系的持票人未履行约定义务；
//                            02、持票人以欺诈、偷盗或者胁迫等手段取得票据；
//                            03、持票人明知有欺诈、偷盗或者胁迫等情形，出于恶意取得票据；
//                            04、持票人明知债务人与出票人或者持票人的前手之间存在抗辩事由而取得票据；
//                            05、持票人因重大过失取得不符合《票据法》规定的票据；
//                            06、超过提示付款期；
//                            07、被法院冻结或收到法院止付通知书；
//                            08、票据未到期；
//                            09、商业承兑汇票承兑人账户余额不足。
//                            10、其他（必须注明）。"
//                            stddshnrsn	拒付备注信息		256	VARCHAR2
//                            stdrcrstyp	追索类型		4	VARCHAR2	"RT00拒付追索 RT01非拒付追索"
                            String styp  = tmpbkReader.readedXElement.getSingleText("stdrcrstyp");
                            if(StringHelper.hasAnyChar(styp)){
                                backDetail.recourseType = "RT00".equals(styp)?"1":"2";
                            }
//                            transferflag	转让标识		5	VARCHAR2
                                backDetail.transFlag = "EM00".equals(tmpbkReader.readedXElement.getSingleText("transferflag")) ? "1" : "0";
                                retAts.writeDetail(backDetail);
                                tmpReadedNum++;
                            }
                        } else {
                            throw new Exception(resultMsg);
                        }
                    } else {
                        throw new Exception(tmpsbMsg.toString());
                    }
                } else {
                    throw new Exception(result[1]);
                }
            }while (tmpReadedNum<totalNum);
        }catch (Exception ex){
            retAts = new RetAtsB005BillBackQry(query.reqHeader);
            retAts.writeStart();
            ex.printStackTrace();
            detail.billNo  = query.detail.billNo;
            detail.respCode = "-1";
            detail.respInfo = ex.getMessage();
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsB006BillStateQry D_B006_BillState_Qeury(ReqB006BillStateQry query) throws Exception {
        RetAtsB006BillStateQry retAts = new RetAtsB006BillStateQry(query.reqHeader);
        retAts.writeStart();
        query.readRecord();
        RetAtsB006BillStateQryDetail detail = new RetAtsB006BillStateQryDetail();
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();
            CRBC01Header header = new CRBC01Header();
            header.tranCode = "110091";
            header.tranTime = new Date();
            writeCommonHeader(xmlWriter,header);
            xmlWriter.writeStartElement("BODY");
//            stdqrycont	客户账号	★	32	VARCHAR2
            xmlWriter.writeElementString("stdqrycont",query.detail.actNum );
//            1-出票交易
//            2-背书交易
//            3-贴现交易
//            4-质押/解质押交易
//            5-提示付款交易
//            6-到期签收及付款交易
//            7-追索交易
            String stdbusstype ="";
            switch (Integer.valueOf(query.detail.busiType)){
                case 1:
                case 2:
                case 3:stdbusstype = "1";break;
                case 4:stdbusstype ="2";break;
                case 5:
                case 6:stdbusstype = "4";break;
                case 10:
                case 11:stdbusstype = "3";break;
                case 12:if("2".equals(query.detail.operType)||"3".equals(query.detail.operType)){
                    stdbusstype ="6";
                }else{
                    stdbusstype = "5";
                }break;
                case 13:
                case 14:stdbusstype = "7";break;
                default:
                    throw new Exception("未知的业务类型: "+query.detail.busiType);
            }
//            stdbusstype	交易类型	★	1	VARCHAR2
            xmlWriter.writeElementString("stdbusstype",stdbusstype );
//            querytype	查询类型	★	1	VARCHAR2	注：0：历史，1：最新
            xmlWriter.writeElementString("querytype","0" );
//            stdacpdatebegin	提交日期起	☆	8	VARCHAR2
            xmlWriter.writeElementString("stdacpdatebegin","" );
//            stdaccpdateend	提交日期止	☆	8	VARCHAR2
            xmlWriter.writeElementString("stdaccpdateend","" );
//            stdpmmoneybegin	票面金额起	☆	15,2	NUMBER
            xmlWriter.writeElementString("stdpmmoneybegin", "");
//            stdpmmoneyend	票面金额止	☆	15,2	NUMBER
            xmlWriter.writeElementString("stdpmmoneyend","" );
//            stdtransno	交易流水号	☆	30	VARCHAR2
            xmlWriter.writeElementString("stdtransno", query.detail.reqSeqID);
//            stdcustacc	电子票据号码	☆	30	VARCHAR2
            if("1".equals(query.detail.busiType)&&"1".equals(query.detail.operType)) {
                xmlWriter.writeElementString("stdcustacc", "");
            }else{
                xmlWriter.writeElementString("stdcustacc", query.detail.billNo);
            }
//            BEGINPOS	翻页数据起始位置	★	10	VARCHAR2
            xmlWriter.writeElementString("BEGINPOS","1");
//            SHOWNUM	翻页一次显示数量	★	10	VARCHAR2
            xmlWriter.writeElementString("SHOWNUM","10");
            xmlWriter.writeEndDocument();
            String[] bankResult = sendToBank(xmlWriter.toXmlString());
            if(bankResult[0].length() ==0){
                StringBuilder tmpsbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1],tmpsbMsg);
                if(tmpBkReader!=null){
                    String resultCode = tmpBkReader.getFirstText("/CRBANK/HEAD/RET_CODE");
                    String resultMsg = tmpBkReader.getFirstText("/CRBANK/HEAD/RET_MSG");
                    if("000000".equals(resultCode)){
                        if(tmpBkReader.read("/CRBANK/BODY/bill_array/STRUCT")){
                            detail.respCode="0";
                            detail.respInfo =tmpBkReader.readedXElement.getSingleText("stdbussstatus");
                            String stdbussflag = tmpBkReader.readedXElement.getSingleText("stdbussflag");
                            if("2".equals(stdbussflag)){
                                detail.transState = stdbussflag;
                            }else {
                                detail.transState = tmpBkReader.readedXElement.getSingleText("stdtrancode");
                                //是撤回操作并且返回撤销成功
                                if (!"1".equals(query.detail.busiType) && "4".equals(query.detail.operType) &&
                                        "A11".equals(detail.transState)) {
                                    detail.transState = "3+" + detail.transState;
                                }
                            }
                            detail.payInfoCode = detail.transState;
//                            detail.billState = tmpBkReader.readedXElement.getSingleText("stdbilstatCode");
                            detail.billState = tmpBkReader.readedXElement.getSingleText("stddraftstatuscode");
                            detail.billNo = tmpBkReader.readedXElement.getSingleText("stdbillnum");
                        }else{
                            detail.respCode ="-1";
                            detail.respInfo = "xml格式异常，获取结果明细失败";
                        }
                    }else{
                        detail.respCode ="-1";
                        detail.respInfo = resultMsg;
                    }
                }else{
                    detail.respCode = "-1";
                    detail.respInfo = tmpsbMsg.toString();
                }
            }else{
                detail.respCode = "-1";
                detail.respInfo = bankResult[1];
            }

        }catch (Exception ex){
            ex.printStackTrace();
            detail.respCode  = "-1";
            detail.respInfo = ex.getMessage();
        }
        retAts.writeDetail(detail);
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsB007BillKzsrQry D_B007_BillKzsr_Query(ReqB007BillKzsrQry query) throws Exception {
        RetAtsB007BillKzsrQry retAts = new RetAtsB007BillKzsrQry(query.reqHeader);
        retAts.writeStart();
        query.readRecord();
        retAts.billNo  = query.detail.billNo;
        int pageNum = getBankConfig().getValueAsInt("eleQryPageNum");
        if(-1==pageNum){
            pageNum =50;
        }
        try {
            int tmpReadedNum =0;
            int page =0;
            int totalNum = 0;
            do {
                page++;
                XmlTextWriter xmlWriter = new XmlTextWriter();
                CRBC01Header header = new CRBC01Header();
                header.tranCode = "110089";
                header.tranTime = new Date();
                writeCommonHeader(xmlWriter, header);
                xmlWriter.writeStartElement("BODY");
//            xmlWriter
//            stdbillnum	电子票号	★	30	VARCHAR2
                xmlWriter.writeElementString("stdbillnum", query.detail.billNo);
//            BEGINPOS	翻页数据起始位置	★	10	VARCHAR2
                xmlWriter.writeElementString("BEGINPOS", page + "");
//            SHOWNUM	翻页一次显示数量	★	10	VARCHAR2
                xmlWriter.writeElementString("SHOWNUM", pageNum+"");
//            stdtransno	交易流水号	★	30	VARCHAR2
                xmlWriter.writeElementString("stdtransno", getQryTransID());
                xmlWriter.writeEndDocument();
                String[] bankResult = sendToBank(xmlWriter.toXmlString());
                if (bankResult[0].length() == 0) {
                    StringBuilder tmpsbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpsbMsg);
                    if (tmpBkReader != null) {
                        String resultCode = tmpBkReader.getFirstText("/CRBANK/HEAD/RET_CODE");
                        String resultMsg = tmpBkReader.getFirstText("/CRBANK/HEAD/RET_Msg");
                        if ("000000".equals(resultCode)) {
                            String totalStr = tmpBkReader.getFirstText("/CRBANK/BODY/TOTALNUM");
                            if (totalNum == 0&&StringHelper.hasAnyChar(totalStr)) {
                                totalNum = Integer.valueOf(totalStr);
                                retAts.respCode = "0";
                                retAts.respInfo = resultMsg;
                                retAts.writeRespInfos();
                            }else if(StringHelper.isNullOrEmpty(totalStr)){
                                throw new Exception("银行返回的记录数为空");
                            }

                            while (tmpBkReader.read("/CRBANK/BODY/bill_array/STRUCT")) {
                                tmpReadedNum++;
                                RetAtsB007BillKzsrQryDetail detail = new RetAtsB007BillKzsrQryDetail();
//                            stdrcvgnme	名称		60	VARCHAR2
                                detail.receName = tmpBkReader.readedXElement.getSingleText("stdrcvgnme");
//                            stdrecrcod	被追索人组织机构代码		20	VARCHAR2
                                detail.receCode = tmpBkReader.readedXElement.getSingleText("stdrecrcod");
//                            stdrcvgacc	帐号		32	VARCHAR2
                                detail.receAct = tmpBkReader.readedXElement.getSingleText("stdrcvgacc");
//                            stdrcvgbnm	开户行行号		12	VARCHAR2
                                detail.receBnkCode = tmpBkReader.readedXElement.getSingleText("stdrcvgbnm");
                                retAts.writeDetail(detail);
                            }
//                        detail.transState = tmpBkReader.getFirstText("/CRBANK/BODY/errcode");
//                        detail.payInfoCode = detail.transState;
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = resultMsg;
                            break;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpsbMsg.toString();
                        break;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = bankResult[1];
                    break;
                }
            }while (tmpReadedNum<totalNum);
        }catch (Exception ex ){
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
        }
        retAts.writeAfter();
        return retAts;
    }

    @Override
    public RetAtsB008HistoricalBillQry D_B008_HistoricalBillQuery(ReqB008HistoricalBillQry query) throws Exception {
        return null;
    }

    @Override
    public RetAtsB009DrawBillQry D_B009_DrawBillQuery(ReqB009DrawBillQry query) throws Exception {
        return null;
    }

    @Override
    public RetAtsB010ProtocolStateQry D_B010_ProtocolStateQuery(ReqB010ProtocolStateQry query) throws Exception {
        return null;
    }

    @Override
    public RetAtsB011TransFlagQry D_B011_TransFlagQuery(ReqB011TransFlagQry query) throws Exception {
        return null;
    }
}
